package common

import (
	"github.com/labstack/echo"
	"reflect"
)

type Validator interface {
	Verify(scene string) error
}

func InputBind(dest interface{}, scene ...string) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			dest := reflect.New(reflect.TypeOf(dest).Elem()).Interface() // 创建一个新的实例，防止不同上下文的输入相互干扰
			if err := c.Bind(dest); err != nil {
				return NewBindDataError()
			} else if vali, ok := dest.(Validator); ok && len(scene) > 0 {
				if err := vali.Verify(scene[0]); err != nil {
					return err
				}
			}
			c.Set("input", dest)
			return next(c)
		}
	}
}
